﻿using System;
using System.Web;

namespace HANS.Utility.Extensions
{
    public static class HttpRequestExtensions
    {
        public static string ToAbsoluteUrl(this HttpRequest request, string relativeUrl)
        {
            return ToAbsoluteUrl(request, request.Url.Authority, relativeUrl);
        }

        public static string ToAbsoluteUrl(this HttpRequest request, string host, string relativeUrl)
        {
            if (!relativeUrl.StartsWith("http://") &&
                !relativeUrl.StartsWith("https://"))
            {
                return String.Format("{0}://{1}/{2}", request.Url.Scheme, host.Trim('/'), relativeUrl.TrimStart('~', '/'));
            }

            return relativeUrl;
        }

        public static string ToAbsoluteUrl(this HttpRequestBase request, string relativeUrl)
        {
            return ToAbsoluteUrl(request, request.Url.Authority, relativeUrl);
        }

        public static string ToAbsoluteUrl(this HttpRequestBase request, string host, string relativeUrl)
        {
            if (!relativeUrl.StartsWith("http://") &&
                !relativeUrl.StartsWith("https://"))
            {
                return String.Format("{0}://{1}/{2}", request.Url.Scheme, host.Trim('/'), relativeUrl.TrimStart('~', '/'));
            }

            return relativeUrl;
        }
    }
}